type storageType = "local" | "session";
interface Ivalue {
  name: string;
  value: any;
  expire: number; //过期时间，毫秒
}
function storage(type: storageType) {
  if (type == "local") {
    return localStorage;
  } else if (type == "session") {
    return sessionStorage;
  }
}
export const setStorage = (type: storageType, label: Ivalue): void => {
  const { name, value, expire } = label;
  const time = Date.now() + expire;
  storage(type).setItem(name, JSON.stringify({ value, expire: time }));
};
export const getStorage = (type: storageType, name: string): any => {
  const value = storage(type).getItem(name);
  if (!value) return null;
  let data = JSON.parse(value);
  if (Date.now() < data.expire) {
    return data;
  } else {
    storage(type).removeItem(name);
    return null;
  }
};

export const removeStorage = (type: storageType, name: string): void => {
  storage(type).removeItem(name);
};
export const ifToken = (): boolean => {
  return getStorage("local", "token") || getStorage("session", "token");
};
export const getToken = (): String => {
  const token = getStorage("local", "token") || getStorage("session", "token");
  if (token) {
    return token.value;
  } else {
    return null;
  }
};
